package com.springlearn.zhoufei.other.spring.demo7;

/**
 * 描述该类- JPA
 *
 * @author zhoufei
 * @class: StudentJDBCTemplate
 * @date 2020/10/3  9:54
 * @Verson 1.0 -2020/10/3  9:54
 * @see
 */

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;

import javax.sql.DataSource;

public class StudentJDBCTemplate implements StudentDAO {
    private DataSource dataSource;
    private JdbcTemplate jdbcTemplateObject;
    
    // 设置数据源
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
        this.jdbcTemplateObject = new JdbcTemplate(dataSource);
    }
    
    @Override
    public void insert() {
        
        Integer age = 12;
        String name = "xiao5";
        String SQL = "insert into Student (name, age) values (?, ?)";
        jdbcTemplateObject.update(SQL, name, age);
        
        if (1 == 1) {
            throw new RuntimeException("异常");
        }
        
        String SQL2 = "update Student set age = ? where id = ?";
        jdbcTemplateObject.update(SQL2, 21, 25);
        
    }
    
    @Override
    public void insert2() {
        Integer age = 12;
        String name = "xiao6";
        String SQL = "insert into Student (name, age) values (?, ?)";
        jdbcTemplateObject.update(SQL, name, age);
        if (1 == 1) {
            // 抛异常，事务由回滚
            int i = 4 / 0;
        }
    }
    
    @Override
    public void insert3() throws Exception {
        try {
            Integer age = 12;
            String name = "xiao7";
            String SQL = "insert into Student (name, age) values (?, ?)";
            jdbcTemplateObject.update(SQL, name, age);
            int i = 4 / 0;
        } catch (Exception e) {
            // 抛出异常，事务没有回滚
            throw new Exception("人为产生异常");// 受检异常（非运行异常）
        }
        
    }
    
    @Override
    public void insert4() {
        try {
            Integer age = 12;
            String name = "xiao8";
            String SQL = "insert into Student (name, age) values (?, ?)";
            jdbcTemplateObject.update(SQL, name, age);
            int i = 4 / 0;
        } catch (Exception e) {
            // 异常抛出，事务回滚
            throw new RuntimeException("人为产生异常");// 运行异常（非受检异常）可以不抛出
        }
        
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insert5() throws Exception {
        try {
            Integer age = 12;
            String name = "xiao9";
            String SQL = "insert into Student (name, age) values (?, ?)";
            jdbcTemplateObject.update(SQL, name, age);
            int i = 4 / 0;
        } catch (Exception e) {
            // 抛出异常，事务回滚
            throw new Exception("人为产生异常");// 受检异常（非运行异常）
        }
        
    }
}